<template>
  <div class="form-container">
    <el-form :model="form" label-width="80px">
      <el-form-item label="资源名称">
        <el-input
          v-model="form.name"
          autocomplete="off"
          placeholder="请输入名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="资源路径">
        <el-input
          v-model="form.url"
          autocomplete="off"
          placeholder="请输入路径"
        ></el-input>
      </el-form-item>
      <el-form-item label="资源分类">
        <el-select v-model="form.categoryId" placeholder="请选择资源分类">
          <el-option
            v-for="item in categories"
            :label="item.name"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资源描述">
        <el-input
          type="textarea"
          :rows="3"
          v-model="form.description"
          autocomplete="off"
          placeholder="请输入描述"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { saveOrUpdateResource } from '@/services/resource'
import { getResourceCategories } from '@/services/resource-category'
export default Vue.extend({
  name: 'ResourceForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    resource: {
      type: Object,
      default: () => null
    }
  },
  data () {
    return {
      form: {
        name: '',
        url: '',
        description: '',
        categoryId: -1
      },
      categories: []
    }
  },
  created () {
    if (this.isEdit) {
      this.form = this.resource
    }
    this.loadResourceCategories()
  },
  methods: {
    async loadResourceCategories () {
      const { data } = await getResourceCategories() as any
      this.categories = data.data
      if (this.form.categoryId === -1 && data.data) {
        this.form.categoryId = data.data[0].id
      }
    },
    onCancel () {
      this.$emit('on-cancel')
    },
    async onSubmit () {
      const { data } = (await saveOrUpdateResource(
        this.form as FromServer.ResourceItem
      )) as any
      if (data) {
        this.$message.success('操作成功')
      } else {
        this.$message.error('操作失败')
      }
      this.$emit('on-submit')
    }
  }
})
</script>

<style lang="scss" scoped>
.form-container {
  width: 80%;
  margin: 0 auto;
}

.dialog-footer {
  text-align: right;
}
</style>
